import Taro from '@tarojs/taro'
import { action, computed, observable } from 'mobx'

import api from '@/api'
import {
  createUserRouterError,
  EUserErrorType,
  getAwemeInfoWithStorage,
  getLoginCode,
  getSystemInfoWithStorage,
} from '@/utils'
import { globalConfig, STORAGE_AWEME_INFO_KEY, STORAGE_SYSTEM_INFO_KEY } from '@/constants'
import { EApplicatStatus, EApplyStatus, EFavourKey, EFavourValue, EVolunteerStatus } from '@/constants/volunteer'

import globalModel from './global'

export type IVolunteerInfo = {
  id?: string;
  // 志愿者姓名
  name?: string;
  // 志愿者状态
  status: EVolunteerStatus;
  // 志愿者申请状态
  applicat_status: EApplicatStatus;
  // 志愿者申请类型
  apply_type: EApplyStatus;
  avatar: string;
  avatar_url: string;
  gender: string;
  birthday: string;
  school?: string;
  // 城市
  city_id: string;
  // 微信号
  wx_code: string;
  mobile: string;
  email: string;
  favour: { [key in EFavourKey]: EFavourValue[] };
  company?: string;
  career?: string;
  introduction: string;
  university?: string;
  university_name?: string;
  major?: string;
  create_date: string;
  isValid?: boolean;
  isVerify?: boolean;
};

export type IAwemeInfo = any;

export class UserModel {
  /** 是否能够自动登录 */
  @observable private _canAutoLogin: boolean = true;
  /** 用户信息 */
  @observable private _userInfo: IVolunteerInfo | null;
  /** 宿主信息 */
  @observable private _awemeInfo: IAwemeInfo | null;

  @computed
  get isLogined() {
    return !!this._userInfo;
  }
  @action
  cleanLogined() {
    Taro.removeStorageSync(STORAGE_AWEME_INFO_KEY);

    this._userInfo = null;
    this._awemeInfo = null;
  }

  @action
  setCanAutoLogin(val: boolean) {
    this._canAutoLogin = val;
  }
  @computed
  get canAutoLogin() {
    return this._canAutoLogin;
  }

  @action
  setUserInfo(info: IVolunteerInfo) {
    this._userInfo = info;
  }

  @computed
  get userInfo() {
    return this._userInfo;
  }

  @action
  setAwemeInfo(info: any) {
    this._awemeInfo = info;
  }
  @computed
  get awemeInfo() {
    return this._awemeInfo;
  }

  @action
  async login() {
    try {
      // 获取用户信息
      await getAwemeInfoWithStorage();
      // 获取设备信息
      await getSystemInfoWithStorage();
    } catch (err) {
      console.error(err);
      throw createUserRouterError(err?.errMsg, EUserErrorType.unknown);
    }

    return await this.autoLogin();
  }

  @action
  async autoLogin() {
    this.setCanAutoLogin(false);

    // 若Stotage存储了账号信息，说明抖音账号已登录，退出或切换抖音账号会清空Storage内容
    const awemeInfo = Taro.getStorageSync(STORAGE_AWEME_INFO_KEY);
    const systemInfo = Taro.getStorageSync(STORAGE_SYSTEM_INFO_KEY);
    if (!awemeInfo || !systemInfo) {
      throw createUserRouterError('账号未登录', EUserErrorType.no_login);
    }

    this.setAwemeInfo(awemeInfo);
    globalModel.setSystemInfo(systemInfo);

    try {
      const code = await getLoginCode();

      const res = await api.lxf.getAuth({ code, ...awemeInfo });
      globalConfig.sid = res.sid;

      const userInfo = await this.getProfile(false);

      this.setUserInfo(userInfo as IVolunteerInfo);
    } catch (err) {
      const statusCode = err?.payload?.response?.statusCode;

      if (statusCode !== undefined && statusCode !== 200) {
        throw createUserRouterError(err?.message, EUserErrorType.unknown);
      }

    }
  }

  @action
  getProfile = async (update?: boolean) => {
    const userInfo = await api.lxf.getVolunteer();
    if (update) {
      this.setUserInfo(userInfo);
    }

    return userInfo;
  };
}

const userModel = new UserModel();

export default userModel;
